package com.gomtel.smartdevice.ui.activity.tools;

import android.graphics.Color;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.gomtel.smartdevice.R;
import com.gomtel.smartdevice.base.WatchAppBaseActivity;
import com.gomtel.smartdevice.bean.UserContent;
import com.gomtel.smartdevice.global.DataClass;
import com.gomtel.smartdevice.moudle.db.entity.BdDataInfo;
import com.gomtel.smartdevice.moudle.db.entity.CaloryDataInfo;
import com.gomtel.smartdevice.moudle.db.entity.EcgDataInfo;
import com.gomtel.smartdevice.moudle.db.entity.HeartRateDataInfo;
import com.gomtel.smartdevice.moudle.event.CommonEvent;
import com.gomtel.smartdevice.utils.ChartUtils;
import com.gomtel.smartdevice.utils.SystemUtil;
import com.gomtel.smartdevice.widget.CalenderUtilsClass;
import com.gomtel.smartdevice.widget.MaxDataIntervalClass;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by Administrator on 2018/5/31 0031.
 * 历史记录
 */

public class MyHistoryActivity extends WatchAppBaseActivity implements View.OnClickListener {

    @BindView(R.id.img_btn_black)
    ImageButton img_btn_black;
    @BindView(R.id.title_name)
    TextView title_name;

    @BindView(R.id.step_chart_bar)
    BarChart step_chart_bar;
    @BindView(R.id.step_center)
    TextView step_center;
    @BindView(R.id.step_all)
    TextView step_all;

    @BindView(R.id.egc_chart_line)
    LineChart egc_chart_line;
    @BindView(R.id.egc_pressure)
    TextView egc_pressure;
    @BindView(R.id.egc_tired)
    TextView egc_tired;

    @BindView(R.id.calory_chart_bar)
    BarChart calory_chart_bar;
    @BindView(R.id.calory_center)
    TextView calory_center;
    @BindView(R.id.calory_all)
    TextView calory_all;

    @BindView(R.id.heart_chart_line)
    LineChart heart_chart_line;
    @BindView(R.id.heart_center)
    TextView heart_center;
    @BindView(R.id.heart_standard)
    TextView heart_standard;

    @BindView(R.id.pvh_chart_line)
    LineChart pvh_chart_line;
    @BindView(R.id.pvh_center)
    TextView pvh_center;
    @BindView(R.id.pvh_standard)
    TextView pvh_standard;

    @BindView(R.id.ldo_chart_line)
    LineChart ldo_chart_line;
    @BindView(R.id.ldo_center)
    TextView ldo_center;
    @BindView(R.id.ldo_standard)
    TextView ldo_standard;


    private ChartUtils chartUtils;
    //    private int[] index;
//    private int[] index2;
    private DataClass dataClass;
    private CalenderUtilsClass calenderUtilsClass;
    private String currentDay;
    private int week = 0;
    private MaxDataIntervalClass maxDataIntervalClass;
    private ArrayList<String> stepCountMonthxAxisLable;
    private int[] stepCountMonthDb;
    int monthStepAll = 0;
    private int[] pressure;
    private ArrayList<String> recentlyTimeList;
    private int[] tired;
    private int[] calory;
    private ArrayList<String> caloryTimeList;
    private int[] heartRate;
    private ArrayList<String> heartRateTimeList;
    private ArrayList<String> bpTimeList;
    private int[] pvhMmHg;
    private int[] ldoMmHg;

    @Override
    protected void registerEvent(CommonEvent commonevent) {

    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_my_history;
    }

    @Override
    protected void initClass() {
        chartUtils = new ChartUtils();
        dataClass = new DataClass(dataManager);
        calenderUtilsClass = new CalenderUtilsClass();
        currentDay = calenderUtilsClass.getCurrentDay(false);
        maxDataIntervalClass = new MaxDataIntervalClass(dataManager);
    }

    @Override
    protected void initData() {
//        index = new int[]{100, 100, 100, 100, 200, 100, 100, 100, 100, 200, 100, 100, 100};
//        index2 = new int[]{10, 80, 200, 120, 220, 260, 40, 60, 80, 120, 140, 100, 100};
        initStepCountMonth();
        initEcgContent();
        initCaloryData();
        initHeartRateData();
        initBpData();
    }

    @Override
    protected void initView() {
        title_name.setText(getString(R.string.my_history));

        chartUtils.setHistoryBarChart(step_chart_bar);
        loadBarChartData(step_chart_bar, stepCountMonthDb, stepCountMonthxAxisLable, getResources().getColor(R.color.blue_style));

        chartUtils.setHistoryChart(egc_chart_line);
        loadMulticlassLineChartData(egc_chart_line, pressure, tired, recentlyTimeList);

        chartUtils.setHistoryBarChart(calory_chart_bar);
        loadBarChartData(calory_chart_bar, calory, caloryTimeList, getResources().getColor(R.color.color_fatigue_orange_2));

        chartUtils.setHistoryChart(heart_chart_line);
        loadLineChartData(heart_chart_line, heartRate, heartRateTimeList);

        chartUtils.setHistoryChart(pvh_chart_line);
        loadLineChartData(pvh_chart_line, pvhMmHg, bpTimeList);

        chartUtils.setHistoryChart(ldo_chart_line);
        loadLineChartData(ldo_chart_line, ldoMmHg, bpTimeList);

    }

    @Override
    protected void initListener() {
        img_btn_black.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_btn_black:
                finish();
                break;
        }
    }

    private void loadLineChartData(final LineChart chart, int[] index, ArrayList<String> xAxisShowLable) {
        chart.setNoDataText("暂无数据");
        ArrayList<LineDataSet> allLinesList = new ArrayList<LineDataSet>();
        ArrayList<Entry> entryList = new ArrayList<Entry>();
        for (int i = 0; i < index.length; i++) {
            //Entry(yValue,xIndex);一个Entry表示一个点，第一个参数为y值，第二个为X轴List的角标
            entryList.add(new Entry(index[i], i));
        }
        //LineDataSet可以看做是一条线
        LineDataSet dataSet = new LineDataSet(entryList, "dataLine");
        dataSet.setLineWidth(0.5f);
        dataSet.setCircleSize(2f);// 显示的圆形大小
        dataSet.setDrawValues(false); // 隐藏折线图每个数据点的值
        dataSet.setValueTextColor(getResources().getColor(R.color.red_style));
        dataSet.setDrawCubic(true);//允许设置平滑曲线
        dataSet.setCircleColor(getResources().getColor(R.color.red_style));
        dataSet.setCircleColorHole(getResources().getColor(R.color.red_style));
        dataSet.setColor(getResources().getColor(R.color.red_style));
        dataSet.setDrawFilled(false);//是否填充折线下方
//        dataSet.setFillColor(Color.rgb(76, 219, 255));//折线图下方填充颜色设置
        dataSet.setFillAlpha(100);
        dataSet.setValueTextSize(24f);
        allLinesList.add(dataSet);
        LineData mChartData = new LineData(xAxisShowLable, allLinesList);
        chart.setData((LineData) mChartData);
        // 设置动画
        chart.setVisibleXRangeMaximum(entryList.size() + 3);
        chart.setVisibleXRangeMinimum(entryList.size());
        chart.animateY(2000);
    }

    private void loadMulticlassLineChartData(final LineChart chart, int[] index, int[] index2, ArrayList<String> xAxisShowLable) {
        chart.setNoDataText("暂无数据");
        ArrayList<LineDataSet> allLinesList = new ArrayList<LineDataSet>();
        ArrayList<Entry> entryList = new ArrayList<Entry>();
        ArrayList<Entry> entryList2 = new ArrayList<Entry>();
        for (int i = 0; i < index.length; i++) {
            entryList.add(new Entry(index[i], i));
        }
        for (int i = 0; i < index2.length; i++) {
            entryList2.add(new Entry(index2[i], i));
        }
        //LineDataSet可以看做是一条线
        LineDataSet dataSet = new LineDataSet(entryList, "dataLine");
        dataSet.setLineWidth(0.5f);
        dataSet.setCircleSize(2f);// 显示的圆形大小
        dataSet.setDrawValues(false); // 隐藏折线图每个数据点的值
        dataSet.setValueTextColor(getResources().getColor(R.color.red_style));
        dataSet.setDrawCubic(false);//允许设置平滑曲线
        dataSet.setCircleColor(getResources().getColor(R.color.red_style));
        dataSet.setCircleColorHole(getResources().getColor(R.color.red_style));
        dataSet.setColor(getResources().getColor(R.color.red_style));
        dataSet.setDrawFilled(false);//是否填充折线下方

        LineDataSet dataSet2 = new LineDataSet(entryList2, "dataLine2");
        dataSet2.setLineWidth(0.5f);
        dataSet2.setCircleSize(2f);// 显示的圆形大小
        dataSet2.setDrawValues(false); // 隐藏折线图每个数据点的值
        dataSet2.setValueTextColor(getResources().getColor(R.color.color_blue_));
        dataSet2.setDrawCubic(false);//允许设置平滑曲线
        dataSet2.setCircleColor(getResources().getColor(R.color.color_blue_));
        dataSet2.setCircleColorHole(getResources().getColor(R.color.color_blue_));
        dataSet2.setColor(getResources().getColor(R.color.color_blue_));
        dataSet2.setDrawFilled(false);//是否填充折线下方

        allLinesList.add(dataSet);
        allLinesList.add(dataSet2);

        LineData mChartData = new LineData(xAxisShowLable, allLinesList);
        chart.setData((LineData) mChartData);
        // 设置动画
        chart.setVisibleXRangeMaximum(entryList.size() + 3);
        chart.setVisibleXRangeMinimum(entryList.size());
        chart.animateY(2000);
    }

    /**
     * 加载并设置柱形图的数据
     *
     * @param chart
     */
    private void loadBarChartData(BarChart chart, int[] index, ArrayList<String> xAxisShowLable, int color) {
        //所有数据点的集合
        ArrayList<BarEntry> entries = new ArrayList<>();
        for (int i = 0; i < index.length; i++) {
            entries.add(new BarEntry(index[i], i));
        }
        //柱形数据的集合
        BarDataSet mBarDataSet = new BarDataSet(entries, "");
        int colors[] = {color};
        mBarDataSet.setColors(colors);//设置每条柱子的颜色
        mBarDataSet.setHighLightAlpha(255);//设置点击后高亮颜色透明度
        mBarDataSet.setHighLightColor(Color.TRANSPARENT);
        mBarDataSet.setValueTextColor(Color.TRANSPARENT);
        mBarDataSet.setBarShadowColor(Color.TRANSPARENT);
        //BarData表示挣个柱形图的数据
        BarData mBarData = new BarData(xAxisShowLable, mBarDataSet);
        chart.setData(mBarData);
        chart.setVisibleXRangeMaximum(xAxisShowLable.size() + 3);
        chart.setVisibleXRangeMinimum(xAxisShowLable.size());
        // 设置动画
        chart.animateY(2000);
    }

    //上月的计步总数
    private void initStepCountMonth() {
        stepCountMonthDb = dataClass.getStepCountMonthDb();
        stepCountMonthxAxisLable = new ArrayList<>();
//        List<String> dayListOfMonth = CalenderUtilsClass.getDayListOfMonth(week - 1);
        List<String> dayListOfMonth = CalenderUtilsClass.getIntervalDate();
        int[] monthStepAllInts = dataClass.getStepCountMonthDb(week);
        for (int i = 0; i < dayListOfMonth.size(); i++) {
            stepCountMonthxAxisLable.add(format(dayListOfMonth.get(i)));
        }
        for (int i = 0; i < monthStepAllInts.length; i++) {
            monthStepAll = monthStepAll + monthStepAllInts[i];
        }
        step_center.setText(new StringBuffer().append("平均每天 ").append(SystemUtil.FormatFloat(monthStepAll, monthStepAllInts.length)).toString());
        step_all.setText(new StringBuffer().append("总计 ").append(monthStepAll));

    }

    //近30次心电
    private void initEcgContent() {
        List<EcgDataInfo> ecgDataInfos = dataManager.queryEcgDataInfo(UserContent.UserName);
        recentlyTimeList = new ArrayList<>();
        int PressureAll = 0;
        int TiredAll = 0;
        if (ecgDataInfos.size() > 30) {
            pressure = new int[30];
            tired = new int[30];
            int ecgCount = ecgDataInfos.size() - 30;
            for (int i = 0; i < 30; i++) {
                EcgDataInfo ecgDataInfo = ecgDataInfos.get(ecgCount + i);
                pressure[i] = Integer.valueOf(ecgDataInfo.getPressureExponent());
                tired[i] = Integer.valueOf(ecgDataInfo.getTiredExponent());
                recentlyTimeList.add(format(ecgDataInfo.getRecentlyTime()));
                PressureAll = PressureAll + pressure[i];
                TiredAll = TiredAll + tired[i];
            }
        } else {
            pressure = new int[ecgDataInfos.size()];
            tired = new int[ecgDataInfos.size()];
            for (int i = 0; i < ecgDataInfos.size(); i++) {
                EcgDataInfo ecgDataInfo = ecgDataInfos.get(i);
                pressure[i] = Integer.valueOf(ecgDataInfo.getPressureExponent());
                tired[i] = Integer.valueOf(ecgDataInfo.getTiredExponent());
                recentlyTimeList.add(format(ecgDataInfo.getRecentlyTime()));
                PressureAll = PressureAll + pressure[i];
                TiredAll = TiredAll + tired[i];
            }
        }
        if (PressureAll != 0 && TiredAll != 0) {
            egc_pressure.setText(new StringBuffer().append("压力指数").append(SystemUtil.FormatFloat(PressureAll, recentlyTimeList.size())));
            egc_tired.setText(new StringBuffer().append("疲劳指数").append(SystemUtil.FormatFloat(TiredAll, recentlyTimeList.size())));
        }

    }

    //近一月卡路里消耗
    private void initCaloryData() {
//        List<String> dayListOfMonth = CalenderUtilsClass.getDayListOfMonth(week - 1);
        List<String> dayListOfMonth = CalenderUtilsClass.getIntervalDate();
        calory = new int[dayListOfMonth.size()];
        caloryTimeList = new ArrayList<>();
        int CaloryAll = 0;
        for (int i = 0; i < dayListOfMonth.size(); i++) {
            CaloryDataInfo caloryDataInfo = dataManager.queryCaloryDataInfo(dayListOfMonth.get(i));
            caloryTimeList.add(format(dayListOfMonth.get(i)));
            if (caloryDataInfo != null) {
                calory[i] = caloryDataInfo.getCaloryCurrent();
            } else {
                calory[i] = 0;
            }
            CaloryAll = CaloryAll + calory[i];
        }

        if (CaloryAll != 0) {
            calory_center.setText(new StringBuffer().append("平均每天 ").append(SystemUtil.FormatFloat(CaloryAll, dayListOfMonth.size())).toString());
            calory_all.setText(new StringBuffer().append("总计 ").append(CaloryAll));
        }

    }

    //近一个月心率记录
    private void initHeartRateData() {
//        List<String> dayListOfMonth = CalenderUtilsClass.getDayListOfMonth(week - 1);
        List<String> dayListOfMonth = CalenderUtilsClass.getIntervalDate();
        heartRate = new int[dayListOfMonth.size()];
        heartRateTimeList = new ArrayList<>();
        int HeartRateAll = 0;
        for (int i = 0; i < dayListOfMonth.size(); i++) {
            HeartRateDataInfo heartRateDataInfo = dataManager.queryHeartRateDataInfo(dayListOfMonth.get(i));
            heartRateTimeList.add(format(dayListOfMonth.get(i)));
            if (heartRateDataInfo != null) {
                heartRate[i] = heartRateDataInfo.getHeratRate();
            } else {
                heartRate[i] = 0;
            }
            HeartRateAll = HeartRateAll + heartRate[i];
        }

        if (HeartRateAll != 0) {
            heart_center.setText(new StringBuffer().append("平均心率 ").append(SystemUtil.FormatFloat(HeartRateAll, dayListOfMonth.size())));
        }

    }

    private void initBpData() {
        List<BdDataInfo> bdDataInfos = dataManager.queryBdDataInfo(UserContent.UserName);
        bpTimeList = new ArrayList<>();
        int pvhMmHgAll = 0;
        int ldoMmHgAll = 0;
        if (bdDataInfos.size() > 30) {
            pvhMmHg = new int[30];
            ldoMmHg = new int[30];
            int ecgCount = bdDataInfos.size() - 30;
            for (int i = 0; i < 30; i++) {
                BdDataInfo bdDataInfo = bdDataInfos.get(ecgCount + i);
                pvhMmHg[i] = Integer.valueOf(bdDataInfo.getPvhMmHg());
                ldoMmHg[i] = Integer.valueOf(bdDataInfo.getLdoMmHg());
                bpTimeList.add(format(bdDataInfo.getRecentlyTime()));
                pvhMmHgAll = pvhMmHgAll + pvhMmHg[i];
                ldoMmHgAll = ldoMmHgAll + ldoMmHg[i];
            }
        } else {
            pvhMmHg = new int[bdDataInfos.size()];
            ldoMmHg = new int[bdDataInfos.size()];
            for (int i = 0; i < bdDataInfos.size(); i++) {
                BdDataInfo bdDataInfo = bdDataInfos.get(i);
                pvhMmHg[i] = Integer.valueOf(bdDataInfo.getPvhMmHg());
                ldoMmHg[i] = Integer.valueOf(bdDataInfo.getLdoMmHg());
                bpTimeList.add(format(bdDataInfo.getRecentlyTime()));
                pvhMmHgAll = pvhMmHgAll + pvhMmHg[i];
                ldoMmHgAll = ldoMmHgAll + ldoMmHg[i];
            }
        }

        if (pvhMmHgAll != 0 && ldoMmHgAll != 0) {
            pvh_center.setText(new StringBuffer().append("平均收缩压 ").append(SystemUtil.FormatFloat(pvhMmHgAll, pvhMmHg.length)));
            ldo_center.setText(new StringBuffer().append("平均舒张压 ").append(SystemUtil.FormatFloat(ldoMmHgAll, ldoMmHg.length)));
        }

    }

    private String format(String day) {
        String[] split = day.split("-");
        return new StringBuffer().append(split[1]).append("-").append(split[2]).toString();
    }

    public ArrayList<String> getXAxisShowLable() {
        ArrayList<String> m = new ArrayList<>();
//        for (int i = 0; i < index.length; i++) {
//            m.add(String.valueOf(i));
//        }
        return m;
    }

}
